import {
  defineComponent,
  ref,
  resolveComponent,
  watch,
  h,
  computed,
} from 'vue';
import {
  getDataPickerProps,
  getEditorEmits,
  useFocusAndBlur,
  useNamespace,
} from '@ibiz-template/vue3-util';
import './ibiz-picker-embed-view.scss';
import { clone } from 'ramda';
import { EventBase } from '@ibiz-template/runtime';
import { PickerEditorController } from '../picker-editor.controller';

export const IBizPickerEmbedView = defineComponent({
  name: 'IBizPickerEmbedView',
  props: getDataPickerProps<PickerEditorController>(),
  emits: getEditorEmits(),
  setup(props, { emit }) {
    const ns = useNamespace('picker-embed-view');

    const c = props.controller!;

    // 视图上下文
    const context = ref(clone(c.context));

    // 视图参数
    const params = ref(clone(c.params));

    // 设置视图参数
    const setViewParam = () => {
      const { context: _context, params: _params } = c.handlePublicParams(
        props.data,
        c.context,
        c.params,
      );
      Object.assign(context.value, _context);
      Object.assign(params.value, _params);
    };
    setViewParam();

    // 监听表单数据，发生变化时重写计算视图参数
    watch(
      () => props.data,
      (newVal, oldVal) => {
        if (newVal !== oldVal) {
          setViewParam();
        }
      },
    );

    // 视图数据改变
    const onViewDataChange = (event: IData[]) => {
      let tempValue: string = '';
      let temText: string = '';
      if (event && Array.isArray(event)) {
        event.forEach((select: IData) => {
          tempValue += `${select.srfkey},`;
          temText += `${select.srfmajortext},`;
        });
        tempValue = tempValue.substring(0, tempValue.length - 1);
        temText = temText.substring(0, temText.length - 1);
        if (c.valueItem) {
          emit('change', tempValue, c.valueItem);
        }
        emit('change', temText);
      }
    };

    // 绑定事件
    const onSelectionChange = (event: EventBase) => {
      onViewDataChange(event.data);
    };

    // 聚焦失焦事件
    const { componentRef: editorRef } = useFocusAndBlur(
      () => emit('focus'),
      () => emit('blur'),
    );

    const pickupViewModel = computed(() => {
      return c.pickupView;
    });

    return {
      ns,
      c,
      context,
      params,
      onSelectionChange,
      editorRef,
      pickupViewModel,
    };
  },
  render() {
    const viewShell = resolveComponent('IBizViewShell');
    return (
      <div class={[this.ns.b()]} ref='editorRef'>
        {this.pickupViewModel
          ? [
              <div class={this.ns.b('view')}>
                {h(viewShell, {
                  context: this.context,
                  params: this.params,
                  viewId: this.c.pickupView?.id,
                  onSelectionChange: this.onSelectionChange,
                })}
              </div>,
              <div class={this.ns.b('value')}>
                {this.$props.value ? (
                  this.$props.value.split(',').map(item => {
                    return <span>{item}; </span>;
                  })
                ) : (
                  <span>{this.c.placeHolder}</span>
                )}
              </div>,
            ]
          : null}
      </div>
    );
  },
});
